package de.clapp.listener;

import de.clapp.CLAppModel;
import de.clapp.ClubMainFragment;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;

public class ClAppTabListener<T extends android.support.v4.app.Fragment> implements ActionBar.TabListener
{
    private android.support.v4.app.Fragment mFragment;

    private final FragmentActivity mActivity;

    private final FragmentManager mManager;

    private android.support.v4.app.FragmentTransaction mTransaction;

    private final String mTag;

    private final Class<T> mClass;

    /**
     * Constructor used each time a new tab is created.
     * 
     * @param activity
     *            The host Activity, used to instantiate the fragment
     * @param tag
     *            The identifier tag for the fragment
     * @param cls
     *            The fragment's Class, used to instantiate the fragment
     */
    public ClAppTabListener(FragmentActivity activity, String tag, Class<T> cls)
    {
        mActivity = activity;
        mTag = tag;
        mClass = cls;
        mManager = activity.getSupportFragmentManager();
        mTransaction = null;
    }
  
    public void onTabSelected(Tab tab, FragmentTransaction ft)
    {
        mTransaction = mManager.beginTransaction();
        // Check if the fragment is already initialized
        if (mFragment == null)
        {
            // If not, instantiate and add it to the activity
            mFragment = Fragment.instantiate(mActivity, mClass.getName());
            if(mClass.equals(ClubMainFragment.class))
            {
                System.out.println("passsssssssssssst");
                CLAppModel.getInstance().setClubMainFragment((ClubMainFragment) mFragment);
                
            }
            mTransaction.add(android.R.id.content, mFragment, mTag);
        }
        else
        {
            // If it exists, simply attach it in order to show it
            mTransaction.attach(mFragment);
        }
        mTransaction.commit();
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft)
    {

        if (mFragment != null)
        {
            mTransaction = mManager.beginTransaction();
            // Detach the fragment, because another one is being attached
            mTransaction.detach(mFragment);
            mTransaction.commit();
        }
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft)
    {
        // User selected the already selected tab. Usually do nothing.
    }
}
